package me.zhangsanfeng.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.zhangsanfeng.base.entity.Product;
import me.zhangsanfeng.base.dao.ProductDao;
import me.zhangsanfeng.base.service.ProductService;
import me.zhangsanfeng.frame.entity.Fields;
import me.zhangsanfeng.frame.entity.Fluzzy;
import me.zhangsanfeng.frame.entity.Order;
import me.zhangsanfeng.frame.util.DataUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author ZhangYao
 * @since 2018-10-18
 */
@Service
@Slf4j
@Transactional(rollbackFor = {Exception.class})
public class ProductServiceImpl extends ServiceImpl<ProductDao, Product> implements ProductService {
    /**
     * 新增,调用mybatis plus service方法
     */
    @Override
    public Product insertProduct(Product product) {
        log.info("service-insertProduct参数{}", product);
        if (save(product)) {
            return getOne(new QueryWrapper<>(product));
        }
        return null;
    }

    /**
     * 批量新增,调用mybatis plus service方法
     */
    @Override
    public int insertBatchProduct(List<Product> products) {
        log.info("service-insertBatchProduct参数{}", products);
        if (saveBatch(products)) {
            return products.size();
        }
        return 0;
    }

    /**
     * 删除,调用mybatis plus service方法
     */
    @Override
    public boolean deleteProduct(Product product) {
        log.info("service-deleteProduct参数{}", product);
        return remove(new QueryWrapper<>(product));
    }

    /**
     * 批量删除
     */
    @Override
    public int deleteBatchProduct(List<Product> products) {
        log.info("service-deleteBatchProduct参数{}", products);
        List<String> ids = null;
        if (products.size() != 0) {
            ids = new ArrayList<>(products.size());
            for (Product product : products) {
                ids.add(product.getId());
            }
        }
        log.info("service-deleteBatchProduct参数ids{}", ids);
        return baseMapper.deleteBatchIds(ids);
    }

    /**
     * 更新一条记录,调用mybatis plus service方法
     */
    @Override
    public boolean update(Product product) {
        log.info("service-update参数{}", product);
        return updateById(product);
    }

    /**
     * 批量更新,调用mybatis plus service方法
     */
    @Override
    public int updateBatchProduct(List<Product> products) {
        log.info("service-updateBatchProduct参数{}", products);
        if (updateBatchById(products)) {
            return products.size();
        }
        return 0;
    }

    /**
     * 查询一条记录,调用mybatis plus service方法
     */
    @Override
    public Product selectProduct(Product product) {
        log.info("service-selectProduct参数{}", product);
        return getOne(queryWrapperHandle(product));
    }

    /**
     * 查询列表
     */
    @Override
    public List<Product> selectListProduct(Product product) {
        log.info("service-selectListProduct参数{}", product);
        QueryWrapper<Product> queryWrapper = queryWrapperHandle(product);
        return list(queryWrapper);
    }

    /**
     * 分页查询列表
     */
    @Override
    public IPage<Product> selectPageProduct(Product product) {
        log.info("service-selectPageProduct参数{}", product);
        Page<Product> page = new Page<>(product.getPageNum(), product.getPageSize());
        QueryWrapper<Product> queryWrapper = queryWrapperHandle(product);
        return page(page, queryWrapper);
    }

    /**
     * 处理where条件下的查询条件构造器
     *
     * @param product
     * @return
     */
    private QueryWrapper<Product> queryWrapperHandle(Product product) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>(product);
        //查询返回字段过滤
        if (DataUtil.isNotEmpty(product.getFields())) {
            Fields fields = product.getFields();
            if (DataUtil.isNotEmpty(fields.getInclude())) {
                queryWrapper.select(DataUtil.camelToUnderline(fields.getInclude()));
            }
            if (DataUtil.isNotEmpty(fields.getExcept())) {
                queryWrapper.excludeColumns(DataUtil.camelToUnderline(fields.getExcept()));
            }
        }
        //where语句操作
        if (DataUtil.isNotEmpty(product.getFluzzy())) {
            Fluzzy fluzzy = product.getFluzzy();
            //where条件in关键字
            if (DataUtil.isNotEmpty(fluzzy.getIn())) {
                String in = fluzzy.getIn();
                String[] ins = in.split("\\|");
                for (int i = 0; i < ins.length; i++) {
                    String[] fields = ins[i].split(":");
                    if (fields.length == 2 && DataUtil.isNotEmpty(fields[1])) {
                        List<Object> list = new ArrayList<>();
                        Object[] split = fields[1].split(",");
                        for (int j = 0; j < split.length; j++) {
                            list.add(split[j]);
                        }
                        queryWrapper.in(fields[0], list);
                    }
                }
                log.info("where条件in关键字SQL结果{}", queryWrapper.toString());
            }
            //where条件or关键字
            if (DataUtil.isNotEmpty(fluzzy.getOr())) {
                String or = fluzzy.getOr();
                String[] ors = or.split(",");
                for (int i = 0; i < ors.length; i++) {
                    String columns = ors[i].split(":")[0];
                    String values = ors[i].split(":")[1];
                    if (DataUtil.isNotEmpty(values)) {
                        queryWrapper.or().eq(DataUtil.camelToUnderline(columns), values);
                    }
                }
                log.info("where条件or关键字SQL结果{}", queryWrapper.toString());
            }

        }
        //where语句条件拼接
        if (DataUtil.isNotEmpty(product.getWhereClause())) {
            String whereClause = product.getWhereClause();
            queryWrapper.last(whereClause);
        }
        //排序
        if (DataUtil.isNotEmpty(product.getOrder())) {
            Order order = product.getOrder();
            StringBuffer fields = new StringBuffer();
            if (DataUtil.isNotEmpty(order.getAsc())) {
                String asc = order.getAsc();
                String[] ascs = asc.split(",");
                for (int i = 0; i < ascs.length; i++) {
                    fields.append(DataUtil.camelToUnderline(ascs[i]));
                    fields.append(",");
                }
                queryWrapper.orderByAsc(fields.deleteCharAt(fields.length() - 1).toString());
            }
            if (DataUtil.isNotEmpty(order.getDesc())) {
                String desc = order.getDesc();
                String[] descs = desc.split(",");
                for (int i = 0; i < descs.length; i++) {
                    fields.append(DataUtil.camelToUnderline(descs[i]));
                    fields.append(",");
                }
                queryWrapper.orderByDesc(fields.deleteCharAt(fields.length() - 1).toString());
            }
        }
        return queryWrapper;
    }
}
